package com.tbit.main.pojo.maintain_performance.group;

import com.tbit.main.constant.enums.ConditionLogic;
import com.tbit.main.constant.enums.PerformanceBizType;
import com.tbit.main.constant.enums.PerformanceRuleType;
import com.tbit.main.pojo.PerformanceRule;
import com.tbit.main.pojo.PerformanceRuleCondition;
import com.tbit.main.pojo.PerformanceRuleGroup;
import com.tbit.main.pojo.maintain_performance.Range;
import com.tbit.main.pojo.maintain_performance.BizRuleGroup;
import com.tbit.main.pojo.maintain_performance.rule.MoveDistanceRule;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 距离绩效规则组
 *
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2025/2/21
 */
@Data
public class MoveDistanceBasedGroup implements BizRuleGroup {
    /**
     * 是否启用
     */
    private Boolean enabled;

    /**
     * 距离对应绩效规则
     */
    private List<MoveDistanceRule> subRules;

    @Override
    public PerformanceRuleGroup toRaw(PerformanceBizType bizType, Integer accountId) {
        PerformanceRuleGroup group = new PerformanceRuleGroup();
        group.setAccountId(accountId);
        group.setBizType(bizType);
        group.setRuleType(PerformanceRuleType.DISTANCE);
        group.setEnabled(enabled);
        group.setRules(new ArrayList<>());

        if (subRules == null) {
            return group;
        }
        for (MoveDistanceRule rule : subRules) {
            PerformanceRule performanceRule = new PerformanceRule();
            performanceRule.setPerformance(rule.getPerformance());
            performanceRule.setConditionLogic(ConditionLogic.AND);
            performanceRule.setConditions(Collections.singletonList(
                    rule.getDistanceMeter().toCondition("distance")
            ));
            group.getRules().add(performanceRule);
        }
        return group;
    }

    @Override
    public void initFromRaw(PerformanceRuleGroup group) {
        setEnabled(group.getEnabled());
        subRules = new ArrayList<>();
        for (PerformanceRule rule : group.getRules()) {
            MoveDistanceRule moveDistanceRule = new MoveDistanceRule();
            for (PerformanceRuleCondition condition : rule.getConditions()) {
                if (condition.getKey().equals("distance")) {
                    moveDistanceRule.setDistanceMeter(Range.from(condition, Integer::parseInt));
                }
            }
            moveDistanceRule.setPerformance(rule.getPerformance());
            subRules.add(moveDistanceRule);
        }
    }
}
